package ru.spies.dbfunctional;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.spies.forms.DBFunctionalForm;
import ru.spies.help.MyLogger;
import ru.spies.pages.ErrorPage;
import ru.spies.pages.SPPage;

/**
 * Servlet implementation class SPcaller
 */
@WebServlet("/SPCaller")
public class SPCaller extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SPCaller() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		ICallFunction caller =DBFunctionalForm.getInstance().getLastCaller();
		if (caller==null){
			out.print(ErrorPage.getInstance().getThisPage());
			MyLogger.getInstance().getLog().error(MyLogger.CAN_T_CALL_THIS_SP);
			return;
		}
		try {
			caller.openConnection();
			caller.fillTable(caller.getResultSet(request), caller.getColumns(false));
			caller.closeConnection();
		} catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			out.print(ErrorPage.getInstance().getThisPage());
			MyLogger.getInstance().getLog().error(MyLogger.EXCEPTION,e);	
			return;
		}
		out.print(SPPage.getInstance(caller).getThisPage());
	}

}
